if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, cameraTarget, scene, renderer, controls;
init();	
animate();
// 计算体积和表面积
function calc_vol_and_area(geo) {
    var x1, x2, x3, y1, y2, y3, z1, z2, z3, i;
    var len = geo.faces.length;
    var totalVolume = 0;
    var totalArea = 0;
    var a, b, c, s;
    var toz, tox, toy;
    for (i = 0; i < len; i++) {
        x1 = geo.vertices[geo.faces[i].a].x;
        y1 = geo.vertices[geo.faces[i].a].y;
        z1 = geo.vertices[geo.faces[i].a].z;
        x2 = geo.vertices[geo.faces[i].b].x;
        y2 = geo.vertices[geo.faces[i].b].y;
        z2 = geo.vertices[geo.faces[i].b].z;
        x3 = geo.vertices[geo.faces[i].c].x;
        y3 = geo.vertices[geo.faces[i].c].y;
        z3 = geo.vertices[geo.faces[i].c].z;
        totalVolume += -x3 * y2 * z1 + x2 * y3 * z1 + x3 * y1 * z2 - x1 * y3 * z2 - x2 * y1 * z3 + x1 * y2 * z3;
        a = geo.vertices[geo.faces[i].a].distanceTo(geo.vertices[geo.faces[i].b]);
        b = geo.vertices[geo.faces[i].b].distanceTo(geo.vertices[geo.faces[i].c]);
        c = geo.vertices[geo.faces[i].c].distanceTo(geo.vertices[geo.faces[i].a]);
        if (!toz) {
            toz = Math.min(a, b, c)
        } else {
            toz = Math.min(toz, a, b, c)
        }
        s = (a + b + c) / 2;
        if (String(Math.sqrt(s * (s - a) * (s - b) * (s - c))) == "NaN") {
            continue
        }
        totalArea += Math.sqrt(s * (s - a) * (s - b) * (s - c))
    }
    alert("totalArea" + totalArea)
    return [Math.abs(totalVolume / 6), totalArea, toz]
}
function init() {

	container = document.createElement( 'div' );
	document.body.appendChild( container );

	camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
	camera.position.set( 3, 0.15, 3 );
	// 控制拖拽
	controls = new THREE.OrbitControls(camera);
    controls.rotateSpeed = 2.0;
    controls.zoomSpeed = 2;
    
	cameraTarget = new THREE.Vector3( 0, -0.25, 0 );

	scene = new THREE.Scene();
	scene.fog = new THREE.Fog( 0x72645b, 2, 15 );

	// Ground
	var plane = new THREE.Mesh(
		new THREE.PlaneBufferGeometry( 40, 40 ),
		new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
	);
	plane.rotation.x = -Math.PI/2;
	plane.position.y = -0.5;
	scene.add( plane );

	plane.receiveShadow = true;

	var loader = new THREE.STLLoader();
	loader.load( 'https://threejs.org/examples/models/stl/binary/pr2_head_tilt.stl', function ( geometry ) {

		var material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } );
		var mesh = new THREE.Mesh( geometry, material );

		// 控制选择角度
		/* mesh.position.set( 0, - 0.25, 0.6 );
		mesh.rotation.set( 0, - Math.PI / 2, 0 );
		mesh.scale.set( 0.5, 0.5, 0.5 ); */

		/* mesh.castShadow = true;
		mesh.receiveShadow = true; */

		scene.add( mesh );
		// 计算的分水岭
		var attrib = geometry.getAttribute("position");
    	if (attrib === undefined) {
            throw new Error("缺少位置属性")
        }
    	var positions = attrib.array;
        var vertices = [];
        for (var i = 0,
            n = positions.length; i < n; i += 3) {
            var x = positions[i];
            var y = positions[i + 1];
            var z = positions[i + 2];
            vertices.push(new THREE.Vector3(x, y, z))
        }
        var faces = [];
        for (var i = 0,
                 n = vertices.length; i < n; i += 3) {
            faces.push(new THREE.Face3(i, i + 1, i + 2))
        }
        geometry.vertices = vertices;
        geometry.faces = faces;
        geometry.computeFaceNormals();
        // geometry.mergeVertices();
        geometry.computeVertexNormals();
        THREE.GeometryUtils.center(geometry);
        
        mesh.useQuaternion = true;
        var axis = new THREE.Vector3(100, 100, 100).normalize();
        var angle = Math.PI / .3;
        var q = (new THREE.Quaternion).setFromAxisAngle(axis, angle);
        mesh.quaternion.copy(q);
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        scene.add(mesh);
        xsize = geometry.boundingBox.max.x - geometry.boundingBox.min.x;
        ysize = geometry.boundingBox.max.y - geometry.boundingBox.min.y;
        zsize = geometry.boundingBox.max.z - geometry.boundingBox.min.z;
        
        alert(xsize + ":" + ysize + ":" + zsize);
        vol_area = calc_vol_and_area(geometry);
        alert("geometry____: " + vol_area);
	} );



	scene.add( new THREE.HemisphereLight( 0x443333, 0x111122 ) );

	addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
	addShadowedLight( 0.5, 1, -1, 0xffaa00, 1 );
	// renderer

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	renderer.gammaInput = true;
	renderer.gammaOutput = true;

	/* renderer.shadowMap.enabled = true;
	renderer.shadowMap.renderReverseSided = false; */

	container.appendChild( renderer.domElement );

	// stats

	stats = new Stats();
	container.appendChild( stats.dom );

	window.addEventListener( 'resize', onWindowResize, false );

}

function addShadowedLight( x, y, z, color, intensity ) {

	var directionalLight = new THREE.DirectionalLight( color, intensity );
	directionalLight.position.set( x, y, z );
	scene.add( directionalLight );

	directionalLight.castShadow = true;

	var d = 1;
	directionalLight.shadow.camera.left = -d;
	directionalLight.shadow.camera.right = d;
	directionalLight.shadow.camera.top = d;
	directionalLight.shadow.camera.bottom = -d;

	directionalLight.shadow.camera.near = 1;
	directionalLight.shadow.camera.far = 4;

	directionalLight.shadow.mapSize.width = 1024;
	directionalLight.shadow.mapSize.height = 1024;

	directionalLight.shadow.bias = -0.005;

}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

	requestAnimationFrame( animate );

	render();
	stats.update();

}

function render() {

	/* var timer = Date.now() * 0.0005;

	camera.position.x = Math.cos( timer ) * 3;
	camera.position.z = Math.sin( timer ) * 3; */

	camera.lookAt( cameraTarget );

	renderer.render( scene, camera );

}